package com.hengpeng.msls.controller.activity;

import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.google.gson.Gson;
import com.hengpeng.common.configuration.ConfigProvider;
import com.hengpeng.common.configuration.ConfigProviderFactory;
import com.hengpeng.common.constant.Constant;
import com.hengpeng.common.exception.ServiceResult;
import com.hengpeng.common.util.StringHelper;
import com.hengpeng.itfinbase.en.RewardRedPacketStatus;
import com.hengpeng.itfinbase.persist.RewardRedpacket;
import com.hengpeng.itfinbase.persist.UserInfo;
import com.hengpeng.msls.controller.BaseController;
import com.hengpeng.msls.util.WeixinUtil;
import com.hengpeng.msls.vo.SessionMember;
import com.hengpeng.msls.vo.activity.RewardRedpacketVo;

@Controller
@RequestMapping(value = "/redpacket")
public class RewardRedpacketController extends BaseController {

    public final static ConfigProvider<String> cp = ConfigProviderFactory
            .getInstance(Constant.HP_COMMON_PROPERTIES_FILEPATH);

    public String appId = cp.getConfigByPrimaryKey("weixin.appId");

    public String appSecret = cp.getConfigByPrimaryKey("weixin.appSecret");
    
    public String h5domain = cp.getConfigByPrimaryKey("weixin.h5domain");
    /**
     * 红包列表页
     */
    @RequestMapping(value="redlist")
    public String listPage(HttpServletRequest request,ModelMap map,Integer type){
        SessionMember session = getSessionMember(request);
        if (session == null) {
            return "/user/login/index.jsp";
        }
        if (type == 2) {
            return "/page/account/reward/investredpacket.jsp";
        }else if(type == 3){
            return "/page/account/reward/shareredpacket.jsp";
        }
        return "/page/account/reward/registerredpacket.jsp";
    }
    
    /**
     * 红包详情分享页
     */
    @RequestMapping(value="share")
    public String share(HttpServletRequest request,ModelMap map,Long redId){
        SessionMember session = getSessionMember(request);
        if (session == null) {
            return "/user/login/index.jsp";
        }
        
        RewardRedpacket redPacket = serviceFactory.getPersistService().get(RewardRedpacket.class,redId);// 获取分享者要分享的红包
        
        map.put("redPacket", redPacket);
        map.put("h5domain", h5domain);
        
        /*************分享红包**************/
        StringBuffer urlBuffer= request.getRequestURL().append("?").append(request.getQueryString());
        String url = urlBuffer.toString();
        if (appId != null && !"".equals(appId)) {
            /**
             * 获取accesstoken
             */
            String accessToken = WeixinUtil.getBaseAccessToken(appId, appSecret);
            System.out.println("----------"+appId+"*************"+appSecret);
            
            /**
             * 获取jsapiticket
             */
            String jsapiTicket = WeixinUtil.getBaseJsapiTicket(appId, accessToken);
            /**
             * 生成js 接口 签名信息
             */
            Map<String, String> jsapiValus = WeixinUtil.sign(jsapiTicket, url);
            map.put("appId", appId);
            map.put("url", jsapiValus.get("url"));
            map.put("nonceStr", jsapiValus.get("nonceStr"));
            map.put("timestamp", jsapiValus.get("timestamp"));
            map.put("signature", jsapiValus.get("signature"));
            
        }
            
        return "/page/account/reward/redpacketDetail.jsp";
    }
    

    /**
     * 获取红包列表（根据红包类型）
     * 
     * @param request
     * @param map
     * @param status
     * @param curPage
     * @return
     */
    @RequestMapping(value = "list")
    @ResponseBody
    public void getRegRedpacket(HttpServletRequest request, ModelMap map, Integer type, String curPage,PrintWriter printWriter,HttpServletResponse response) {
        SessionMember session = getSessionMember(request);
        Map<String , List<?>> dataMap = new HashMap<String, List<?>>();
        List<Integer> pagecount = new ArrayList<Integer>();
        UserInfo userInfo = session.getUser();
        int int_curPage = (!StringHelper.isEmpty(curPage) ? Integer.parseInt(curPage) : 1);
        ServiceResult<List<RewardRedpacketVo>> serviceResult = serviceFactory.getActivityService()
                .findRegRedpacketByStatus(userInfo.getId(), type, int_curPage, 10);// 根据红包类型type查询红包
        
        pagecount.add(serviceResult.getReturnListSize());
        dataMap.put("list", serviceResult.getReturnValue());
        dataMap.put("pageCount", pagecount);
        Gson gson = new Gson();
        printWriter.write(gson.toJson(dataMap)); 
        printWriter.flush(); 
        printWriter.close();
        
    }
    
    /**
     * 跳转到可用红包 20151112 lugaofei
     */
    @RequestMapping(value="getRedpacket")
    public String getRedpacket(HttpServletRequest request,ModelMap map,String borrowId){
        map.addAttribute("borrowId", borrowId);
        return "/page/account/reward/canuseredpacket.jsp";
    }
    /**
     * 获取可用红包 20151112 lugaofei
     */
    @RequestMapping(value="canuseRedpacket")
    @ResponseBody
    public void getCanuseRedpacket(HttpServletRequest request,ModelMap map,String curPage,PrintWriter printWriter){
        SessionMember session = getSessionMember(request);
        Map<String , List<?>> dataMap = new HashMap<String, List<?>>();
        List<Integer> pagecount = new ArrayList<Integer>();
        int int_curPage = (!StringHelper.isEmpty(curPage) ? Integer.parseInt(curPage) : 1);
        UserInfo user = session.getUser();
        ServiceResult<List<RewardRedpacketVo>> serviceResult = serviceFactory.getActivityService().findRewardRedpacket(user.getId(), RewardRedPacketStatus.CANUSE, int_curPage, 10);
        map.put("dataList", serviceResult.getReturnValue());
        pagecount.add(serviceResult.getReturnListSize());
        dataMap.put("list", serviceResult.getReturnValue());
        dataMap.put("pageCount", pagecount);
        Gson gson = new Gson();
        printWriter.write(gson.toJson(dataMap)); 
        printWriter.flush(); 
        printWriter.close();
    }
}
